package org.infinitest.swingui;

import javax.swing.*;
import javax.swing.tree.TreePath;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import org.infinitest.TestEvent;
import org.infinitest.swingui.TestEventSelectionListener;

class ResultClickListener extends MouseAdapter
{
  private TestEventSelectionListener selectionListener;

  public ResultClickListener()
  {
    // TODO Continue refactoring out event handling to support click to source in IDE plugins
    selectionListener = new TestEventSelectionListener()
    {
      public void expandPath(JTree tree, TreePath path)
      {
        tree.expandPath(path);
      }

      public void showInfoPane(TestEvent event)
      {
        new EventInfoFrame(event).setVisible(true);
      }
    };
  }

  public ResultClickListener(TestEventSelectionListener selectionListener)
  {
    this.selectionListener = selectionListener;
  }

  @Override
  public void mouseClicked(MouseEvent e)
  {
    if (e.getClickCount() != 2)
      return;

    JTree tree = (JTree) e.getSource();
    TreePath path = tree.getClosestPathForLocation(e.getX(), e.getY());
    Object treeNode = path.getLastPathComponent();
    if (treeNode instanceof TestEvent)
    {
      selectionListener.showInfoPane((TestEvent) treeNode);
    }
    else
    {
      selectionListener.expandPath(tree, path);
    }
  }
}
